import { GetUserOpenId } from '@/api/user';
import Taro from '@tarojs/taro';

const interceptor = async function (chain) {
    const requestParams = chain.requestParams
    let openId: string | undefined

    //接口前置获取openid
    if (!requestParams.url.includes('/api/user/openid')) {
        openId = Taro.getStorageSync('openId');

        if (!openId) openId = await GetUserOpenId()
        if (!openId) return Taro.showModal({
            title: '系统错误',
            content: `获取openid 失败`
        })
        Taro.setStorageSync("openId", openId)
    }


    requestParams.header = {
        ...requestParams.header,
        openid: Taro.getStorageSync('openId') || "",
        token: Taro.getStorageSync("token") || ""
    }

    //设置全局请求域名
    requestParams.url = `${APP_API_URL}${requestParams.url}`
    return chain.proceed(requestParams)
        .then(res => {
            //针对code， 清楚本地缓存
            if (res.data.code === -1) Taro.clearStorageSync()
            if (res.data.code === 603) {
                Taro.showToast({ title: '当前用户已被禁用', icon: 'none' })
                return Promise.reject(res.data)
            }
            if (res.data.state === 'fail') {
                res.data.msg && Taro.showToast({ title: res.data.msg, icon: 'none' })
                return Promise.reject(res.data)
            }
            return res.data
        })
}


Taro.addInterceptor(interceptor)